import http from '../utils/http';
import { ALL_CATEGORIES,NEW_CATEGORY,DELETE_CATEGORY,UPDATE_CATEGORY } from './types';

export function setNewCategory(result) {
  return {
    type: NEW_CATEGORY,
    result
  };
}

export function setCategories(result) {
  return {
    type: ALL_CATEGORIES,
    result
  };
}

export function setDeletedCategory(result){
  return {
    type:DELETE_CATEGORY,
    result
  };
}

export function updateCategoryTitle(result){
  return {
    type:UPDATE_CATEGORY,
    result
  }
}

// export function setSelectedCategoryID(id){
//   return {
//     type:SELECTED_CATEGORY_ID,
//     id
//   }
// }

export function createCategory(data){
  return dispatch => {
    return http.post('/api/categories/create', data).then(res => {
          if (res.data.code !== 10200 ){
            dispatch(setNewCategory({data:null,state:"failed", message:res.data.message}));
          }else {
            data['id'] = res.data.body.ID;
            dispatch(setNewCategory({data:data,state:"success", message:res.data.message}));
          }
          return res.data.body.ID;
        });
  }
}

export function getCategories(){
    return dispatch => {
      return http.get('/api/categories').then(res => {
            console.log(res.data.body);
            if (res.data.code !== 10200 ){
              dispatch(setCategories({data:[],state:"failed", message:res.data.message}));
            }else {
              dispatch(setCategories({data:res.data.body.categories,state:"success", message:res.data.message}));
            }
          });
    }
}

export function deleteCategory(id){
    return dispatch => {
      return http.post('/api/categories/delete',{  id :parseInt(id,10 ) }).then(res => {
            if (res.data.code !== 10200 ){
                dispatch(setDeletedCategory({data:[],state:"failed", message:res.data.message}));
            }else {
              dispatch(setDeletedCategory({data:id,state:"success", message:res.data.message}));
            }
          });
    }
}

export function updateCategory(data) {
  return dispatch => {
      return http.post('/api/categories/update', data ).then(res => {
            if (res.data.code !== 10200 ){
                dispatch(updateCategoryTitle({data:[],state:"failed", message:res.data.message}));
            }else {
              dispatch(updateCategoryTitle({data:data,state:"success", message:res.data.message}));
            }
          });
    }
}
